package com.bdtop.dbl;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.bdtop.dbl.ui.activities.main.SplashScreenActivity;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.Preferences;

public class BaseActivity extends FragmentActivity {

	protected LayoutInflater mInflater;

	protected final long mediumAnimTime = 400;

	protected TextView txWaitingMessage;
	protected TitleBar mTitleBar;
	protected ImageView waitingFlag;
	protected Handler mHandler = new Handler();

	protected String loginSign;

	@Override protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		DBLApplication.getInstance().addActivity(this);
		DBLDebug.logd("act onCreate");

		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		txWaitingMessage = (TextView) findViewById(R.id.tx_waiting_message);
		if (txWaitingMessage != null) {
			txWaitingMessage.setOnClickListener(onWaitClickListenter);
		}

		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		if (mTitleBar != null) {
			mTitleBar.setBelongActivity(this);
		}

		loginSign = Preferences.getLoginSign(this);

	}

	public OnClickListener onWaitClickListenter = new OnClickListener() {
		@Override public void onClick(View arg0) {
			txWaitingMessage.startAnimation(AnimationUtils.loadAnimation(BaseActivity.this, R.anim.fade_out));
			txWaitingMessage.setVisibility(View.GONE);
		}
	};

	protected void showWaitingFlag() {
		if (mTitleBar != null) mTitleBar.showWaitingFlag();
	}

	protected void hiddenWaitingFlag() {
		if (mTitleBar != null) mTitleBar.hiddenWaitingFlag();
	}

	public void setAndShowWaitingMessage(int resId) {
		setAndShowWaitingMessage(getString(resId));
	}

	public void setAndShowWaitingMessage(String resId) {
		if (txWaitingMessage != null) {
			if (View.VISIBLE != txWaitingMessage.getVisibility()) txWaitingMessage.setVisibility(View.VISIBLE);
			txWaitingMessage.setText(resId);
		}
	}

	public void clearAndHiddenWaitingMessage() {
		if (txWaitingMessage != null) {
			txWaitingMessage.setVisibility(View.GONE);
			txWaitingMessage.setText("");
		}
	}

	public void hiddenWaitingMessage() {
		if (txWaitingMessage != null) {
			txWaitingMessage.setVisibility(View.GONE);
		}
	}

	public void showWaitingMessage() {
		if (txWaitingMessage != null) {
			if (!TextUtils.isEmpty(txWaitingMessage.getText())) {
				txWaitingMessage.setVisibility(View.VISIBLE);
			}
		}
	}

	public TextView getWaitingText() {
		return txWaitingMessage;
	}

	protected Button initMenu(int resId, OnClickListener listener) {
		if (mTitleBar == null) {
			DBLDebug.loge("the title bar not init - can not add menu");
			return null;
		}
		Button btnMenu = new Button(BaseActivity.this);
		btnMenu.setText(resId);
		btnMenu.setBackgroundResource(R.drawable.selector_title_blue_btn_bg);
		btnMenu.setTextColor(Color.WHITE);
		btnMenu.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		btnMenu.setOnClickListener(listener);
		mTitleBar.addMenu(btnMenu);
		return btnMenu;
	}

	protected void setTitleText(int resId) {
		if (mTitleBar != null) {
			mTitleBar.setTitle(resId);
		}
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		DBLDebug.logd("app onDestroy " + getClass().getSimpleName());
		DBLApplication.getInstance().remove(this);
	}

	public void showToast(String text) {
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
	}

	public void showToast(int id) {
		Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
	}

	private Dialog mDialog;
	private TextView txMassage;

	public void dismissDialog() {
		if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
	}

	public void setNewWaitingMessage(int messageId) {
		if (mDialog != null && mDialog.isShowing()) {
			txMassage.setText(getString(messageId));
		}
	}

	public void showWaitingDialog(int messageId, boolean canCancel, boolean shadow) {
		showWaitingDialog(getString(messageId), canCancel, shadow);
	}

	public void showWaitingDialog(String message, boolean canCancel, boolean shadow) {
		View content = LayoutInflater.from(this).inflate(R.layout.dialog_waiting, null);
		content.findViewById(R.id.icon).startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_forever));

		txMassage = (TextView) content.findViewById(R.id.massage);
		txMassage.setText(message);

		mDialog = new Dialog(this, shadow ? R.style.Theme_Light_NoTitle_Dialog : R.style.Theme_Light_NoTitle_NoShadow_Dialog);

		mDialog.setContentView(content);
		mDialog.setCanceledOnTouchOutside(canCancel);
		mDialog.setCancelable(canCancel);
		mDialog.setOnCancelListener(new OnCancelListener() {
			@Override public void onCancel(DialogInterface arg0) {
			}
		});
		mDialog.show();
	}

	@Override protected void onStart() {
		super.onStart();
		DBLDebug.logd("act onStart :  " + getClass().getSimpleName());

		boolean fromBack = Preferences.getStartFromBack();
		if (fromBack) {
			Preferences.saveStartFromBack(false);
			
			long lastTime = Preferences.getGuaQiTime();
			long i = System.currentTimeMillis() - lastTime;
			DBLDebug.logd("app lastTime :  " + lastTime + ",  jian ge ::" + i + "ms");
			if (i > 300 * 1000) {
				DBLDebug.logd("app 超过时间5分钟 销毁所有活动");
				DBLApplication.getInstance().exit();
				
				SplashScreenActivity.launch(this);
			} else {
				DBLDebug.logd("app OK时间");
			}
		} else {
			DBLDebug.logd("app 仍在使用");
		}
	}

	@Override protected void onStop() {
		super.onStop();
		/******************** 长时间挂起需要释放地图资源 ********************/
		if (!isAppOnForeground()) {
			// app 进入后台
			// 全局变量isActive = false 记录当前已经进入后台
			DBLDebug.logd("app 进入后台");
			Preferences.saveStartFromBack(true);
			Preferences.saveGuaQiTime(System.currentTimeMillis());
		} else {
			DBLDebug.logd("app 仍然在使用");
		}
	}
	
	/**
	 * 程序是否在前台运行
	 * 
	 * @return
	 */
	public boolean isAppOnForeground() {
		// Returns a list of application processes that are running on the
		// device

		ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = getApplicationContext().getPackageName();

		List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
		if (appProcesses == null) return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}
}
